package com.example.as_sum.util.toast;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

/**
 * Created by ran on 2016/11/10.
 */

public class ToastUtil {
    private Context mContext;
    private WindowManager mWindowManager;
    private View mView;
    private int mDuration;
    public  ToastUtil(Context context){
        mContext=context;
        mWindowManager= (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    }
    public static ToastUtil makeText(Context context,String text,int duration){
        ToastUtil toast=new ToastUtil(context);
        //使用系统默认的Toast的布局
        View view=android.widget.Toast.makeText(context,text,duration).getView();
        if(view!=null){
            TextView tv= (TextView) view.findViewById(android.R.id.message);
            tv.setText(text);
        }
        toast.mView=view;
        toast.mDuration=duration;
        return toast;
    }
    public ToastUtil makeText(Context context,int resId,int duration)throws Resources.NotFoundException{
        return makeText(context,context.getResources().getString(resId),duration);
    }
    public void show(){
        if(mView!=null){
            WindowManager.LayoutParams params=new WindowManager.LayoutParams();
            params.width= WindowManager.LayoutParams.WRAP_CONTENT;
            params.height=WindowManager.LayoutParams.WRAP_CONTENT;
            //标志位，系统层级 应用window层级1-99，子window1000-1999，系统2000-2999
            //window有三种类型：应用window，子window（设置view的token，view.getWindowToken()），系统window。
            //Toast的级别更高，所以他会显示在Dialog上，不会被Dialog遮盖
            params.type=WindowManager.LayoutParams.TYPE_TOAST;
            //系统的Toast动画
            params.windowAnimations=android.R.style.Animation_Toast;
            params.format= PixelFormat.TRANSLUCENT;// TRANSLUCENT支持透明
            params.gravity= Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL;
            //FLAG_NOT_FOCUSABLE焦点
            params.flags=WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                    | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                    |WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
            mWindowManager.addView(mView,params);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(mView!=null){
                        mWindowManager.removeView(mView);
                        mView=null;
                        mWindowManager=null;
                    }
                }
            },mDuration);
        }
    }
}
